<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use backend\models\Role;
use backend\models\Node;
class RoleController extends BaseController{
	public $layout = 'common';
	public function actionAdd()
	{
		$role = new Role;
		if(Yii::$app->request->isPost){
			$data = Yii::$app->request->post();
			$role->role_name = $data['role_name'];
			$role->insert();
			$role_id = Yii::$app->db->getLastInsertID();
			foreach($data['node_id'] as $key => $val){
				Yii::$app->db->createCommand()->insert('e_role_node', [
									    'role_id' => $role_id,
									    'node_id' => $val,
									])->execute();
			}
			$this->refresh();
		}
		$nodes = Node::find()->asArray()->all();
		$roles = Yii::$app->db->createCommand('SELECT * FROM e_role')
            ->queryAll();
        foreach($roles as $key => $val){
        	$node_name = Yii::$app->db->createCommand("select * from e_node where node_id in (select node_id from e_role_node where role_id = ".$val['role_id'].")")->queryAll();
        	$roles[$key]['node'] = $node_name;
        }
		return $this->render('add',['nodes'=>$nodes,'roles'=>$roles]);
	}
}